import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import random
from collections import defaultdict
import openpyxl
from openpyxl.styles import Font
import json
import os
from datetime import datetime


class ScrollableFrame(ttk.Frame):
    """可滚动的Frame容器 - 现代化样式"""

    def __init__(self, container, *args, **kwargs):
        super().__init__(container, *args, **kwargs)

        # 创建画布和滚动条
        self.canvas = tk.Canvas(self, 
                               highlightthickness=0,
                               bg='#ffffff',
                               relief='flat')
        self.scrollbar = ttk.Scrollbar(self, 
                                      orient="vertical", 
                                      command=self.canvas.yview,
                                      style='TScrollbar')
        self.scrollable_frame = ttk.Frame(self.canvas, style='TFrame')

        # 配置画布
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(
                scrollregion=self.canvas.bbox("all")
            )
        )

        # 创建窗口
        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=self.scrollbar.set)

        # 绑定鼠标滚轮事件（仅当鼠标在画布上时才滚动）
        self.canvas.bind("<Enter>", lambda _: self.canvas.bind_all("<MouseWheel>", self._on_mousewheel))
        self.canvas.bind("<Leave>", lambda _: self.canvas.unbind_all("<MouseWheel>"))

        # 布局
        self.canvas.pack(side="left", fill="both", expand=True)
        self.scrollbar.pack(side="right", fill="y")

    def _on_mousewheel(self, event):
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")


class GuanDanTournament:
    def __init__(self, root):
        self.root = root
        self.root.title("掼蛋比赛管理系统 V2.0 Pro")
        self.root.geometry("1200x900")  # 增大窗口尺寸
        self.root.minsize(1000, 700)  # 设置最小尺寸
        
        # 设置现代化的配色方案
        self.root.configure(bg='#f8f9fa')  # 浅灰白背景
        
        # 设置窗口图标
        icon = os.path.join(os.path.dirname(__file__), 'images', 'favicon.ico')
        try:
            self.root.iconbitmap(icon)
        except:
            pass  # 如果图标文件不存在，忽略错误

        # 比赛数据
        self.teams = []
        self.rounds = []
        self.current_round = 0
        self.max_rounds = tk.IntVar(value=3)  # 改为变量，可以手动设置
        self.team_scores = defaultdict(lambda: {"big": 0, "small": 0})
        self.team_info = {}  # 包含队伍名称和队员信息
        self.history = []
        self.timer_running = False
        self.remaining_time = 0
        self.team_entries = []  # 保存所有Entry部件
        self.start_time = None  # 比赛开始时间
        self.current_round_results = []  # 当前轮次结果
        self.edit_mode = False  # 编辑模式标志

        # 设置现代化样式主题
        self.setup_styles()
        
        # 创建界面
        self.create_widgets()
        self.results_submitted = False  # 添加提交状态标志

    def setup_styles(self):
        """设置现代化的样式主题"""
        style = ttk.Style()
        
        # 设置主题（优雅的蓝灰色系）
        try:
            style.theme_use('clam')  # 使用clam主题作为基础
        except:
            pass
        
        # 配色方案 - 现代蓝灰色系
        colors = {
            'primary': '#2c3e50',      # 深蓝灰
            'secondary': '#3498db',    # 明亮蓝
            'success': '#27ae60',      # 绿色
            'warning': '#f39c12',      # 橙色
            'danger': '#e74c3c',       # 红色
            'light': '#ecf0f1',        # 浅灰
            'dark': '#34495e',         # 深灰
            'white': '#ffffff',        # 纯白
            'text_primary': '#2c3e50', # 主文本色
            'text_secondary': '#7f8c8d', # 次要文本色
            'border': '#bdc3c7',       # 边框色
            'hover': '#34495e'         # 悬停色
        }
        
        # 设置框架样式
        style.configure('TFrame', 
                       background='#ffffff',
                       relief='flat')
        
        # 设置标签样式
        style.configure('TLabel',
                       background='#ffffff',
                       foreground=colors['text_primary'],
                       font=('Microsoft YaHei UI', 9))
        
        # 设置标题样式
        style.configure('Title.TLabel',
                       background='#ffffff',
                       foreground=colors['primary'],
                       font=('Microsoft YaHei UI', 12, 'bold'))
        
        # 设置小标题样式
        style.configure('Subtitle.TLabel',
                       background='#ffffff',
                       foreground=colors['secondary'],
                       font=('Microsoft YaHei UI', 10, 'bold'))
        
        # 设置按钮样式
        style.configure('TButton',
                       padding=(12, 8),
                       font=('Microsoft YaHei UI', 9),
                       focuscolor='none')
        
        # 主要按钮样式
        style.configure('Primary.TButton',
                       background=colors['secondary'],
                       foreground='white',
                       borderwidth=0,
                       focuscolor='none')
        
        # 成功按钮样式
        style.configure('Success.TButton',
                       background=colors['success'],
                       foreground='white',
                       borderwidth=0,
                       focuscolor='none')
        
        # 警告按钮样式
        style.configure('Warning.TButton',
                       background=colors['warning'],
                       foreground='white',
                       borderwidth=0,
                       focuscolor='none')
        
        # 危险按钮样式
        style.configure('Danger.TButton',
                       background=colors['danger'],
                       foreground='white',
                       borderwidth=0,
                       focuscolor='none')
        
        # 设置标签框样式
        style.configure('TLabelframe',
                       background='#ffffff',
                       borderwidth=1,
                       relief='solid',
                       bordercolor=colors['border'])
        
        style.configure('TLabelframe.Label',
                       background='#ffffff',
                       foreground=colors['primary'],
                       font=('Microsoft YaHei UI', 10, 'bold'))
        
        # 设置输入框样式
        style.configure('TEntry',
                       fieldbackground='#ffffff',
                       borderwidth=1,
                       insertcolor=colors['primary'],
                       font=('Microsoft YaHei UI', 9))
        
        # 设置下拉框样式
        style.configure('TCombobox',
                       fieldbackground='#ffffff',
                       background='#ffffff',
                       borderwidth=1,
                       arrowcolor=colors['secondary'],
                       font=('Microsoft YaHei UI', 9))
        
        # 设置列表框样式
        style.configure('TListbox',
                       background='#ffffff',
                       foreground=colors['text_primary'],
                       selectbackground=colors['secondary'],
                       selectforeground='white',
                       borderwidth=1,
                       font=('Microsoft YaHei UI', 9))
        
        # 设置滚动条样式
        style.configure('TScrollbar',
                       background=colors['light'],
                       troughcolor=colors['light'],
                       borderwidth=0,
                       arrowcolor=colors['secondary'],
                       darkcolor=colors['border'],
                       lightcolor=colors['border'])
        
        # 设置分隔线样式
        style.configure('TSeparator',
                       background=colors['border'])
        
        # 特殊样式 - 对阵框架
        style.configure('Match.TLabelframe',
                       background='#ffffff',
                       borderwidth=2,
                       relief='solid',
                       bordercolor=colors['secondary'])
        
        # 特殊样式 - 结果框架
        style.configure('Result.TLabelframe',
                       background='#ffffff',
                       borderwidth=2,
                       relief='solid',
                       bordercolor=colors['success'])
        
        # 特殊样式 - 计时器框架
        style.configure('Timer.TLabelframe',
                       background='#ffffff',
                       borderwidth=2,
                       relief='solid',
                       bordercolor=colors['warning'])
        
        # 特殊样式 - 控制框架
        style.configure('Control.TLabelframe',
                       background='#ffffff',
                       borderwidth=2,
                       relief='solid',
                       bordercolor=colors['primary'])
        
        # 特殊样式 - 历史框架
        style.configure('History.TLabelframe',
                       background='#ffffff',
                       borderwidth=2,
                       relief='solid',
                       bordercolor=colors['dark'])
        
        # 保存颜色配置供其他方法使用
        self.colors = colors

    def create_widgets(self):
        # 主标题栏
        title_frame = ttk.Frame(self.root, style='TFrame')
        title_frame.pack(fill=tk.X, padx=20, pady=(15, 5))
        
        title_label = ttk.Label(title_frame, 
                               text="🏆 掼蛋比赛管理系统", 
                               style='Title.TLabel')
        title_label.pack()
        
        # 主容器框架 - 使用更好的间距
        self.main_frame = ttk.Frame(self.root, style='TFrame', padding="20")
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 左侧面板 (设置和控制) - 进一步增加宽度，给更多空间
        self.left_panel = ttk.Frame(self.main_frame, style='TFrame', width=520)  # 从500增加到520
        self.left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10), pady=5)
        self.left_panel.pack_propagate(False)  # 保持固定宽度

        # 右侧面板 (对阵和结果) - 进一步减少空间给左侧使用
        self.right_panel = ttk.Frame(self.main_frame, style='TFrame')
        self.right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=(10, 0), pady=5)

        # 参赛队伍设置 - 使用新样式，给更多高度和更好的布局
        self.setup_frame = ttk.LabelFrame(self.left_panel, 
                                          text="👥 参赛队伍设置", 
                                          style='TLabelframe',
                                          padding="12")
        self.setup_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 6))

        # 队伍数量设置 - 使用更好的布局
        control_frame = ttk.Frame(self.setup_frame, style='TFrame')
        control_frame.grid(row=0, column=0, columnspan=4, sticky="ew", pady=(0, 10))

        # 使用两行布局，第一行：队伍数量和轮次设置
        settings_row1 = ttk.Frame(control_frame, style='TFrame')
        settings_row1.pack(fill=tk.X, pady=(0, 6))
        
        ttk.Label(settings_row1, text="队伍数量:", style='TLabel').pack(side=tk.LEFT, padx=(0, 6))
        self.team_count = ttk.Combobox(settings_row1, 
                                      values=[str(i) for i in range(4, 101, 2)], 
                                      state="readonly", 
                                      width=6,
                                      style='TCombobox')
        self.team_count.pack(side=tk.LEFT, padx=(0, 15))
        self.team_count.current(2)  # 默认8队

        ttk.Label(settings_row1, text="比赛轮次:", style='TLabel').pack(side=tk.LEFT, padx=(0, 6))
        self.rounds_entry = ttk.Entry(settings_row1, width=6, style='TEntry')
        self.rounds_entry.pack(side=tk.LEFT)
        self.rounds_entry.insert(0, "3")

        # 第二行：操作按钮，使用更好的布局
        button_row = ttk.Frame(control_frame, style='TFrame')
        button_row.pack(fill=tk.X, pady=(2, 0))
        
        ttk.Button(button_row, 
                  text="🚀 生成队伍", 
                  command=self.generate_teams,
                  style='Primary.TButton').pack(side=tk.LEFT, padx=(0, 8), fill=tk.X, expand=True)
        
        ttk.Button(button_row, 
                  text="💾 保存信息", 
                  command=self.save_team_info,
                  style='Success.TButton').pack(side=tk.LEFT, fill=tk.X, expand=True)

        # 队伍名称和队员输入区域 - 使用ScrollableFrame
        self.team_input_scroll = ScrollableFrame(self.setup_frame)
        self.team_input_scroll.grid(row=1, column=0, columnspan=4, pady=(5, 0), sticky="nsew")
        self.team_input_frame = self.team_input_scroll.scrollable_frame

        # 配置setup_frame的网格权重
        self.setup_frame.rowconfigure(1, weight=1)
        self.setup_frame.columnconfigure(0, weight=1)

        # 计时和控制面板 - 重新设计为垂直布局，给每个更多空间
        timer_control_container = ttk.Frame(self.left_panel, style='TFrame')
        timer_control_container.pack(fill=tk.X, pady=(0, 6))

        # 倒计时设置 - 优化布局
        self.timer_frame = ttk.LabelFrame(timer_control_container, 
                                          text="⏱️ 比赛计时", 
                                          style='Timer.TLabelframe',
                                          padding="10")
        self.timer_frame.pack(fill=tk.X, pady=(0, 4))

        # 计时器输入和控制 - 水平布局但更紧凑
        timer_input_frame = ttk.Frame(self.timer_frame, style='TFrame')
        timer_input_frame.pack(fill=tk.X, pady=(0, 6))
        
        ttk.Label(timer_input_frame, text="时间(分):", style='TLabel').pack(side=tk.LEFT)
        self.minutes_entry = ttk.Entry(timer_input_frame, width=5, style='TEntry')
        self.minutes_entry.pack(side=tk.LEFT, padx=(4, 8))
        self.minutes_entry.insert(0, "50")

        ttk.Button(timer_input_frame, 
                  text="▶️ 开始", 
                  command=self.start_timer,
                  style='Warning.TButton').pack(side=tk.LEFT)
        
        # 计时器显示 - 调整字体大小和位置
        self.timer_label = ttk.Label(self.timer_frame, 
                                    text="00:00", 
                                    font=('Consolas', 16, 'bold'),
                                    foreground='#e74c3c',
                                    background='#ffffff')
        self.timer_label.pack()

        # 比赛控制 - 独立区域，使用更好的布局
        self.control_frame = ttk.LabelFrame(timer_control_container, 
                                            text="🎮 比赛控制", 
                                            style='Control.TLabelframe',
                                            padding="10")
        self.control_frame.pack(fill=tk.X)

        # 按钮使用3列网格布局，更紧凑
        buttons = [
            ("🏁 新轮次", self.start_new_round, 'Primary.TButton'),
            ("📈 查看排名", self.show_ranking, 'TButton'),
            ("🔄 重置比赛", self.reset_tournament, 'Danger.TButton'),
            ("📄 导出Excel", self.export_to_excel, 'TButton'),
            ("ℹ️ 关于产品", self.show_about, 'TButton'),
            ("🔍 验证积分", self.validate_and_fix_scores_with_ui, 'Success.TButton'),  # 改为新的UI方法
        ]
        
        for i, (text, command, style) in enumerate(buttons):
            row = i // 3
            col = i % 3
            btn = ttk.Button(self.control_frame, 
                           text=text, 
                           command=command,
                           style=style)
            btn.grid(row=row, column=col, padx=1, pady=1, sticky="ew")
        
        # 设置列权重
        for col in range(3):
            self.control_frame.columnconfigure(col, weight=1)

        # 比赛历史记录 - 优化高度和布局
        self.history_frame = ttk.LabelFrame(self.left_panel, 
                                            text="📜 比赛历史", 
                                            style='History.TLabelframe',
                                            padding="10")
        self.history_frame.pack(fill=tk.BOTH, expand=True)

        self.history_scroll = ScrollableFrame(self.history_frame)
        self.history_scroll.pack(fill=tk.BOTH, expand=True, pady=(0, 6))
        
        # 使用更现代的列表框，增加高度到10行
        self.history_listbox = tk.Listbox(self.history_scroll.scrollable_frame, 
                                         height=10,  # 进一步增加高度
                                         font=('Microsoft YaHei UI', 9),
                                         bg='#ffffff',
                                         fg='#2c3e50',
                                         selectbackground='#3498db',
                                         selectforeground='#ffffff',
                                         borderwidth=1,
                                         relief='solid')
        self.history_listbox.pack(fill=tk.BOTH, expand=True)

        # 历史记录按钮 - 更紧凑的布局
        history_button_frame = ttk.Frame(self.history_frame, style='TFrame')
        history_button_frame.pack(fill=tk.X)

        ttk.Button(history_button_frame, 
                  text="📁 加载", 
                  command=self.load_tournament,
                  style='TButton').pack(side=tk.LEFT, padx=(0, 4), expand=True, fill=tk.X)
        
        ttk.Button(history_button_frame, 
                  text="💾 保存", 
                  command=self.save_tournament,
                  style='Success.TButton').pack(side=tk.RIGHT, expand=True, fill=tk.X)

        # 对阵和结果输入区域 (右侧面板) - 使用新样式
        self.match_frame = ttk.LabelFrame(self.right_panel, 
                                          text="⚔️ 当前轮次对阵", 
                                          style="Match.TLabelframe",
                                          padding="15")
        self.match_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))

        self.match_scroll = ScrollableFrame(self.match_frame)
        self.match_scroll.pack(fill=tk.BOTH, expand=True)
        self.match_content = self.match_scroll.scrollable_frame

        self.result_frame = ttk.LabelFrame(self.right_panel, 
                                           text="🏆 比赛结果", 
                                           style="Result.TLabelframe",
                                           padding="15")
        self.result_frame.pack(fill=tk.BOTH, expand=True)

        self.result_scroll = ScrollableFrame(self.result_frame)
        self.result_scroll.pack(fill=tk.BOTH, expand=True)
        self.result_content = self.result_scroll.scrollable_frame

    def show_about(self):
        """显示关于产品的信息窗口"""
        about_window = tk.Toplevel(self.root)
        about_window.title("关于掼蛋比赛管理系统")
        about_window.geometry("600x850")
        about_window.resizable(False, False)
        about_window.configure(bg='#f8f9fa')
        
        # 设置窗口图标
        try:
            icon = os.path.join(os.path.dirname(__file__), 'images', 'favicon.ico')
            about_window.iconbitmap(icon)
        except:
            pass

        # 主框架 - 使用更现代的设计
        main_frame = tk.Frame(about_window, bg='#ffffff', relief='raised', bd=1)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

        # 产品标题 - 使用更好的样式
        title_frame = tk.Frame(main_frame, bg='#ffffff')
        title_frame.pack(pady=(20, 10))
        
        tk.Label(title_frame, 
                text="🏆 掼蛋比赛管理系统", 
                font=('Microsoft YaHei UI', 18, 'bold'),
                fg=self.colors['primary'],
                bg='#ffffff').pack()

        # 版本信息
        version_frame = tk.Frame(main_frame, bg='#ffffff')
        version_frame.pack(pady=5)
        
        tk.Label(version_frame, 
                text="版本: V2.0.0 Pro", 
                font=('Microsoft YaHei UI', 12),
                fg=self.colors['secondary'],
                bg='#ffffff').pack()

        # 分隔线
        separator1 = tk.Frame(main_frame, height=2, bg=self.colors['border'])
        separator1.pack(fill=tk.X, pady=15)

        # 产品说明
        description_frame = tk.Frame(main_frame, bg='#ffffff')
        description_frame.pack(pady=10)
        
        description = """🎆 本系统是为掼蛋比赛设计的专业管理工具

✨ 主要功能：
• 参赛队伍管理
• 比赛轮次设置
• 比赛结果记录
• 实时排名统计
• 数据导出功能
• 积分验证修复

💯 适用于各类掼蛋比赛的组织和管理工作。"""
        
        tk.Label(description_frame, 
                text=description, 
                font=('Microsoft YaHei UI', 10),
                fg=self.colors['text_primary'],
                bg='#ffffff',
                justify=tk.CENTER).pack()

        # 分隔线
        separator2 = tk.Frame(main_frame, height=2, bg=self.colors['border'])
        separator2.pack(fill=tk.X, pady=15)

        # 开发者信息
        dev_frame = tk.Frame(main_frame, bg='#ffffff')
        dev_frame.pack(pady=10)
        
        tk.Label(dev_frame, 
                text="👨‍💻 开发者信息", 
                font=('Microsoft YaHei UI', 14, 'bold'),
                fg=self.colors['primary'],
                bg='#ffffff').pack(pady=(0, 10))
        
        dev_info = [
            ("👤 作者", "郭晨"),
            ("🏢 开发团队", "燃源网络技术"),
            ("📧 联系方式", "rysoft@139.com"),
            ("📅 发布日期", "2025-05-20")
        ]
        
        for label, value in dev_info:
            info_line = tk.Frame(dev_frame, bg='#ffffff')
            info_line.pack(fill=tk.X, pady=2)
            
            tk.Label(info_line, 
                    text=f"{label}: {value}", 
                    font=('Microsoft YaHei UI', 10),
                    fg=self.colors['text_secondary'],
                    bg='#ffffff').pack()

        # 分隔线
        separator3 = tk.Frame(main_frame, height=2, bg=self.colors['border'])
        separator3.pack(fill=tk.X, pady=15)

        # 二维码区域 - 优化布局，给二维码更多空间
        qr_container = tk.Frame(main_frame, bg='#ffffff')
        qr_container.pack(pady=20, fill=tk.X)

        # 左侧二维码区域
        left_qr_frame = tk.Frame(qr_container, bg='#ffffff')
        left_qr_frame.pack(side=tk.LEFT, padx=20, fill=tk.BOTH, expand=True)

        tk.Label(left_qr_frame, 
                text="📱 扫码咨询定制开发", 
                font=('Microsoft YaHei UI', 11, 'bold'),
                fg=self.colors['primary'],
                bg='#ffffff').pack(pady=(0, 10))

        # 左侧二维码图片 - 增加容器大小
        left_qr_container = tk.Frame(left_qr_frame, bg='#ffffff', width=200, height=200)
        left_qr_container.pack(expand=True)
        left_qr_container.pack_propagate(False)
        
        try:
            weRq = os.path.join(os.path.dirname(__file__), 'images', 'we_rq.png')
            qr_image = tk.PhotoImage(file=weRq)
            # 缩放图片以适应容器
            qr_label = tk.Label(left_qr_container, image=qr_image, bg='#ffffff')
            qr_label.image = qr_image  # 保持引用
            qr_label.pack(expand=True)
        except Exception as e:
            tk.Label(left_qr_container, 
                    text="[微信二维码图片]", 
                    font=('Microsoft YaHei UI', 9),
                    fg=self.colors['text_secondary'],
                    bg='#ffffff').pack(expand=True)

        # 垂直分割线
        separator_v = tk.Frame(qr_container, width=2, bg=self.colors['border'])
        separator_v.pack(side=tk.LEFT, fill=tk.Y, padx=20)

        # 右侧小程序码区域
        right_qr_frame = tk.Frame(qr_container, bg='#ffffff')
        right_qr_frame.pack(side=tk.LEFT, padx=20, fill=tk.BOTH, expand=True)

        tk.Label(right_qr_frame, 
                text="📋 扫码查看案例信息", 
                font=('Microsoft YaHei UI', 11, 'bold'),
                fg=self.colors['primary'],
                bg='#ffffff').pack(pady=(0, 10))

        # 右侧小程序码图片 - 增加容器大小
        right_qr_container = tk.Frame(right_qr_frame, bg='#ffffff', width=200, height=200)
        right_qr_container.pack(expand=True)
        right_qr_container.pack_propagate(False)
        
        try:
            miniRq = os.path.join(os.path.dirname(__file__), 'images', 'mini_rq.png')
            mini_image = tk.PhotoImage(file=miniRq)
            mini_label = tk.Label(right_qr_container, image=mini_image, bg='#ffffff')
            mini_label.image = mini_image  # 保持引用
            mini_label.pack(expand=True)
        except Exception as e:
            tk.Label(right_qr_container, 
                    text="[小程序二维码]", 
                    font=('Microsoft YaHei UI', 9),
                    fg=self.colors['text_secondary'],
                    bg='#ffffff').pack(expand=True)

        # 关闭按钮 - 使用更好的样式
        close_frame = tk.Frame(main_frame, bg='#ffffff')
        close_frame.pack(pady=30)
        
        close_btn = tk.Button(close_frame, 
                             text="✖️ 关闭", 
                             command=about_window.destroy,
                             font=('Microsoft YaHei UI', 11, 'bold'),
                             bg=self.colors['danger'],
                             fg='white',
                             relief='flat',
                             padx=40,
                             pady=10,
                             cursor='hand2')
        close_btn.pack()

    def generate_teams(self):
        # 清除旧的队伍名称输入框
        for widget in self.team_input_frame.winfo_children():
            widget.destroy()

        # 创建新的队伍名称和队员输入框
        count = int(self.team_count.get())
        self.teams = list(range(1, count + 1))
        self.team_entries = []  # 重置保存的Entry部件

        # 设置最大轮次
        try:
            max_rounds = int(self.rounds_entry.get())
            if max_rounds <= 0:
                raise ValueError
            self.max_rounds.set(max_rounds)
        except ValueError:
            messagebox.showerror("错误", "请输入有效的轮次数！")
            return

        # 表头 - 使用更好的样式
        header_frame = ttk.Frame(self.team_input_frame, style='TFrame')
        header_frame.grid(row=0, column=0, columnspan=4, sticky="ew", pady=(0, 10))
        
        headers = [
            ("🏆 队伍", 0),
            ("🎯 名称", 1), 
            ("👤 队员1", 2),
            ("👤 队员2", 3)
        ]
        
        for text, col in headers:
            ttk.Label(header_frame, 
                     text=text, 
                     style='Subtitle.TLabel').grid(row=0, column=col, padx=8, sticky=tk.W)

        for i in range(count):
            row = i + 1

            # 队伍标签 - 使用更好的样式
            team_label = ttk.Label(self.team_input_frame, 
                                  text=f"第{i + 1}队:", 
                                  style='TLabel')
            team_label.grid(row=row, column=0, sticky=tk.E, padx=(0, 8), pady=5)

            # 队伍名称 - 使用新样式
            name_entry = ttk.Entry(self.team_input_frame, 
                                  width=15, 
                                  style='TEntry',
                                  font=('Microsoft YaHei UI', 9))
            name_entry.grid(row=row, column=1, padx=5, pady=5, sticky="ew")
            name_entry.insert(0, f"队伍{i + 1}")

            # 队员1 - 使用新样式
            player1_entry = ttk.Entry(self.team_input_frame, 
                                     width=15, 
                                     style='TEntry',
                                     font=('Microsoft YaHei UI', 9))
            player1_entry.grid(row=row, column=2, padx=5, pady=5, sticky="ew")
            player1_entry.insert(0, f"队员A{i + 1}")

            # 队员2 - 使用新样式
            player2_entry = ttk.Entry(self.team_input_frame, 
                                     width=15, 
                                     style='TEntry',
                                     font=('Microsoft YaHei UI', 9))
            player2_entry.grid(row=row, column=3, padx=5, pady=5, sticky="ew")
            player2_entry.insert(0, f"队员B{i + 1}")

            # 保存Entry部件
            self.team_entries.append((name_entry, player1_entry, player2_entry))
        
        # 设置列权重，使输入框可以自适应宽度
        for col in range(1, 4):
            self.team_input_frame.columnconfigure(col, weight=1)

    def save_team_info(self):
        # 保存队伍名称和队员信息
        self.team_info = {}

        for team_num, entries in zip(self.teams, self.team_entries):
            name_entry, player1_entry, player2_entry = entries

            self.team_info[team_num] = {
                "name": name_entry.get(),
                "players": [player1_entry.get(), player2_entry.get()]
            }

        messagebox.showinfo("成功", "队伍信息已保存！")

    def start_timer(self):
        if self.timer_running:
            return

        try:
            minutes = int(self.minutes_entry.get())
            if minutes <= 0:
                raise ValueError
        except ValueError:
            messagebox.showerror("错误", "请输入有效的分钟数！")
            return

        self.remaining_time = minutes * 60
        self.timer_running = True
        self.start_time = datetime.now()  # 记录比赛开始时间
        self.update_timer()

    def update_timer(self):
        if not self.timer_running:
            return

        mins, secs = divmod(self.remaining_time, 60)
        time_str = f"{mins:02d}:{secs:02d}"
        self.timer_label.config(text=time_str)

        if self.remaining_time <= 0:
            self.timer_running = False
            messagebox.showinfo("时间到", "比赛时间已结束！")
            return

        self.remaining_time -= 1
        self.root.after(1000, self.update_timer)

    def start_new_round(self):
        self.results_submitted = False  # 重置提交状态
        if not self.teams:
            messagebox.showerror("错误", "请先设置参赛队伍！")
            return

        if self.current_round >= self.max_rounds.get():
            messagebox.showerror("错误", f"比赛已经结束，最多进行{self.max_rounds.get()}轮！")
            return

        # 清除旧的比赛输入框
        for widget in self.match_content.winfo_children():
            widget.destroy()

        # 确定对阵
        if self.current_round == 0:
            # 第一轮随机对阵
            random.shuffle(self.teams)
            matches = [(self.teams[i], self.teams[i + 1]) for i in range(0, len(self.teams), 2)]
        else:
            # 后续轮次按积分高低配对
            sorted_teams = sorted(self.teams,
                                  key=lambda x: (-self.team_scores[x]["big"], -self.team_scores[x]["small"]))
            matches = [(sorted_teams[i], sorted_teams[i + 1]) for i in range(0, len(sorted_teams), 2)]

        self.rounds.append(matches)
        self.current_round += 1

        # 记录历史
        self.history.append({
            "round": self.current_round,
            "matches": matches,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
        self.update_history_list()

        # 显示对阵标题 - 使用更好的样式
        title_frame = ttk.Frame(self.match_content, style='TFrame')
        title_frame.grid(row=0, column=0, columnspan=8, pady=15, sticky="ew")
        
        ttk.Label(title_frame, 
                 text=f"🏁 第 {self.current_round} 轮对阵",
                 style='Title.TLabel').pack()

        # 表头 - 使用更现代的设计
        header_frame = ttk.Frame(self.match_content, style='TFrame')
        header_frame.grid(row=1, column=0, columnspan=8, pady=(10, 15), sticky="ew")
        
        # 创建表头标签
        headers = [
            ("🏆 队伍1", 0, 2),
            ("⚔️", 2, 1),
            ("🏆 队伍2", 3, 2),
            ("🎯 结果", 5, 3)
        ]
        
        for text, col, span in headers:
            label = ttk.Label(header_frame, 
                            text=text, 
                            style='Subtitle.TLabel')
            label.grid(row=0, column=col, columnspan=span, padx=10, pady=5)

        # 添加对阵和结果输入框
        self.result_entries = []
        for i, (team1, team2) in enumerate(matches):
            base_row = i * 4 + 2  # 每场比赛占用4行空间

            # 创建比赛卡片背景
            match_card = ttk.Frame(self.match_content, style='TFrame', relief='raised', borderwidth=1)
            match_card.grid(row=base_row, column=0, columnspan=8, sticky="ew", padx=10, pady=8)
            match_card.columnconfigure(0, weight=1)
            match_card.columnconfigure(1, weight=0)
            match_card.columnconfigure(2, weight=1)
            match_card.columnconfigure(3, weight=0)

            # 比赛编号
            match_number = ttk.Label(match_card, 
                                   text=f"第 {i+1} 场", 
                                   style='Subtitle.TLabel')
            match_number.grid(row=0, column=0, columnspan=4, pady=(10, 5))

            # 显示队伍1信息
            team1_frame = ttk.Frame(match_card, style='TFrame')
            team1_frame.grid(row=1, column=0, padx=15, pady=10, sticky="ew")
            
            team1_info = self.team_info.get(team1, {})
            ttk.Label(team1_frame, 
                     text=f"🏆 {team1}队: {team1_info.get('name', '')}",
                     style='TLabel',
                     font=('Microsoft YaHei UI', 10, 'bold')).pack(anchor=tk.W)
            ttk.Label(team1_frame, 
                     text=f"👤 {', '.join(team1_info.get('players', []))}",
                     style='TLabel',
                     foreground='#7f8c8d').pack(anchor=tk.W, pady=(2, 0))

            # VS 标签
            vs_frame = ttk.Frame(match_card, style='TFrame')
            vs_frame.grid(row=1, column=1, padx=20, pady=10)
            
            ttk.Label(vs_frame, 
                     text="⚔️\nVS", 
                     style='Subtitle.TLabel',
                     justify=tk.CENTER).pack()

            # 显示队伍2信息
            team2_frame = ttk.Frame(match_card, style='TFrame')
            team2_frame.grid(row=1, column=2, padx=15, pady=10, sticky="ew")
            
            team2_info = self.team_info.get(team2, {})
            ttk.Label(team2_frame, 
                     text=f"🏆 {team2}队: {team2_info.get('name', '')}",
                     style='TLabel',
                     font=('Microsoft YaHei UI', 10, 'bold')).pack(anchor=tk.W)
            ttk.Label(team2_frame, 
                     text=f"👤 {', '.join(team2_info.get('players', []))}",
                     style='TLabel',
                     foreground='#7f8c8d').pack(anchor=tk.W, pady=(2, 0))

            # 结果输入区域
            result_frame = ttk.Frame(match_card, style='TFrame')
            result_frame.grid(row=1, column=3, padx=15, pady=10, sticky="ew")
            
            # 结果1输入
            result1_container = ttk.Frame(result_frame, style='TFrame')
            result1_container.pack(fill=tk.X, pady=(0, 5))
            
            ttk.Label(result1_container, 
                     text=f"{team1}队结果:", 
                     style='TLabel').pack(side=tk.LEFT)
            
            result_entry1 = ttk.Combobox(result1_container,
                                        values=["A+", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"],
                                        state="readonly", 
                                        width=6,
                                        style='TCombobox')
            result_entry1.pack(side=tk.RIGHT)
            result_entry1.bind("<MouseWheel>", lambda e: "break")

            # 结果2输入
            result2_container = ttk.Frame(result_frame, style='TFrame')
            result2_container.pack(fill=tk.X)
            
            ttk.Label(result2_container, 
                     text=f"{team2}队结果:", 
                     style='TLabel').pack(side=tk.LEFT)
            
            result_entry2 = ttk.Combobox(result2_container,
                                        values=["A+", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"],
                                        state="readonly", 
                                        width=6,
                                        style='TCombobox')
            result_entry2.pack(side=tk.RIGHT)
            result_entry2.bind("<MouseWheel>", lambda e: "break")

            self.result_entries.append((team1, team2, result_entry1, result_entry2))

        # 添加提交按钮 - 使用更好的样式
        button_container = ttk.Frame(self.match_content, style='TFrame')
        button_container.grid(row=len(matches) * 4 + 2, column=0, columnspan=8, pady=20)

        # 创建按钮框架
        button_frame = ttk.Frame(button_container, style='TFrame')
        button_frame.pack()

        ttk.Button(button_frame, 
                  text="✅ 提交本轮结果", 
                  command=self.submit_results,
                  style='Success.TButton').pack(side=tk.LEFT, padx=(0, 15))
        
        ttk.Button(button_frame, 
                  text="✏️ 修改结果", 
                  command=self.enable_edit_mode,
                  style='Warning.TButton').pack(side=tk.LEFT)

    def enable_edit_mode(self):
        """启用编辑模式"""
        if not self.results_submitted:
            messagebox.showwarning("提示", "请先提交结果再修改！")
            return

        self.edit_mode = True
        for _, _, entry1, entry2 in self.result_entries:
            entry1.config(state="readonly")
            entry2.config(state="readonly")

        messagebox.showinfo("提示", "现在可以修改结果，修改后请重新提交")

    def submit_results(self):
        # 处理比赛结果
        if self.results_submitted and not self.edit_mode:
            messagebox.showwarning("重复提交", "请勿重复提交！")
            return

        round_results = []

        # 如果是编辑模式，先撤销之前的结果
        if self.edit_mode:
            for result in self.current_round_results:
                team1 = result["team1"]
                team2 = result["team2"]
                self.team_scores[team1]["big"] -= result["big1"]
                self.team_scores[team1]["small"] -= result["small1"]
                self.team_scores[team2]["big"] -= result["big2"]
                self.team_scores[team2]["small"] -= result["small2"]
            self.edit_mode = False

        self.current_round_results = []  # 清空当前轮次结果

        for team1, team2, entry1, entry2 in self.result_entries:
            result1 = entry1.get()
            result2 = entry2.get()

            if not result1 or not result2:
                messagebox.showerror("错误", "请填写所有比赛结果！")
                return

            # 计算小分
            small1 = self.card_to_score(result1)
            small2 = self.card_to_score(result2)

            # 计算大分
            if small1 > small2:
                big1, big2 = 2, 0
            elif small1 < small2:
                big1, big2 = 0, 2
            else:
                big1, big2 = 1, 1

            # 更新总分
            self.team_scores[team1]["big"] += big1
            self.team_scores[team1]["small"] += small1

            self.team_scores[team2]["big"] += big2
            self.team_scores[team2]["small"] += small2

            # 记录本轮结果
            round_result = {
                "team1": team1,
                "team2": team2,
                "result1": result1,
                "result2": result2,
                "big1": big1,
                "big2": big2,
                "small1": small1,
                "small2": small2
            }
            round_results.append(round_result)
            self.current_round_results.append(round_result)

        # 更新历史记录 - 增强健壮性
        if self.history and len(self.history) > 0 and self.history[-1]["round"] == self.current_round:
            self.history[-1]["results"] = round_results
        else:
            # 如果找不到匹配的历史记录，记录警告信息
            print(f"警告：无法找到第{self.current_round}轮的历史记录，将创建新记录")
            self.history.append({
                "round": self.current_round,
                "matches": [(team1, team2) for team1, team2, _, _ in self.result_entries],
                "results": round_results,
                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            })

        self.results_submitted = True  # 标记为已提交
        # 禁用所有结果输入框
        for _, _, entry1, entry2 in self.result_entries:
            entry1.config(state="disabled")
            entry2.config(state="disabled")

        # 显示结果
        self.show_results()
        
        # 自动验证积分准确性
        self.validate_and_fix_scores()
        
        messagebox.showinfo("成功", "本轮结果已提交！")

    def card_to_score(self, card):
        # 将牌面转换为小分（修正为+13）
        card_values = {
            "A+": 15, "A": 14, "K": 13, "Q": 12, "J": 11,
            "10": 10, "9": 9, "8": 8, "7": 7, "6": 6,
            "5": 5, "4": 4, "3": 3, "2": 2
        }
        return card_values.get(card, 0) + 13  # 修正为+13

    def validate_and_fix_scores_with_ui(self):
        """验证并修复积分计算错误 - UI版本"""
        if not self.team_scores or not self.history:
            messagebox.showinfo("验证积分", "没有比赛数据可验证！")
            return
        
        # 显示进度窗口
        progress_window = tk.Toplevel(self.root)
        progress_window.title("验证积分")
        progress_window.geometry("400x300")
        progress_window.resizable(False, False)
        progress_window.configure(bg='#f8f9fa')
        
        # 设置窗口图标
        try:
            icon = os.path.join(os.path.dirname(__file__), 'images', 'favicon.ico')
            progress_window.iconbitmap(icon)
        except:
            pass
        
        # 窗口居中
        progress_window.transient(self.root)
        progress_window.grab_set()
        
        # 主框架
        main_frame = tk.Frame(progress_window, bg='#ffffff', relief='raised', bd=1)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 标题
        title_label = tk.Label(main_frame, 
                              text="🔍 积分验证中...", 
                              font=('Microsoft YaHei UI', 14, 'bold'),
                              fg=self.colors['primary'],
                              bg='#ffffff')
        title_label.pack(pady=(10, 20))
        
        # 进度信息
        progress_text = tk.Text(main_frame, 
                               height=8, 
                               width=45,
                               font=('Microsoft YaHei UI', 9),
                               bg='#f8f9fa',
                               fg=self.colors['text_primary'],
                               relief='flat',
                               state='disabled')
        progress_text.pack(pady=(0, 15))
        
        def log_message(message):
            progress_text.config(state='normal')
            progress_text.insert(tk.END, message + '\n')
            progress_text.see(tk.END)
            progress_text.config(state='disabled')
            progress_window.update()
        
        log_message("🚀 开始验证积分...")
        
        # 保存原始积分作为对比
        original_scores = {team: dict(score) for team, score in self.team_scores.items()}
        log_message(f"📄 已保存原始积分数据")
        
        # 重新计算所有积分
        self.team_scores = defaultdict(lambda: {"big": 0, "small": 0})
        log_message(f"🔄 清零积分，开始重新计算...")
        
        # 遍历所有历史记录重新计算
        for round_num, round_data in enumerate(self.history, 1):
            if "results" in round_data:
                log_message(f"🏁 正在验证第{round_num}轮...")
                for result in round_data["results"]:
                    team1 = result["team1"]
                    team2 = result["team2"]
                    
                    # 重新计算小分
                    small1 = self.card_to_score(result["result1"])
                    small2 = self.card_to_score(result["result2"])
                    
                    # 重新计算大分
                    if small1 > small2:
                        big1, big2 = 2, 0
                    elif small1 < small2:
                        big1, big2 = 0, 2
                    else:
                        big1, big2 = 1, 1
                    
                    # 累加积分
                    self.team_scores[team1]["big"] += big1
                    self.team_scores[team1]["small"] += small1
                    self.team_scores[team2]["big"] += big2
                    self.team_scores[team2]["small"] += small2
        
        # 检查是否有差异
        has_difference = False
        differences = []
        
        for team in self.teams:
            if team in original_scores:
                original = original_scores[team]
                current = dict(self.team_scores[team])
                if (original["big"] != current["big"] or original["small"] != current["small"]):
                    has_difference = True
                    diff_msg = f"队伍{team}: 原{original['big']}/{original['small']} → 现{current['big']}/{current['small']}"
                    differences.append(diff_msg)
                    log_message(f"⚠️ {diff_msg}")
        
        if has_difference:
            log_message(f"\n🔧 发现{len(differences)}个积分差异，已自动修复！")
            title_label.config(text="✅ 积分修复完成", fg=self.colors['success'])
            
            # 更新结果显示
            if hasattr(self, 'result_content'):
                self.show_results()
                
        else:
            log_message("\n✅ 积分验证通过，无异常！")
            title_label.config(text="✅ 积分验证正常", fg=self.colors['success'])
        
        # 关闭按钮
        close_frame = tk.Frame(main_frame, bg='#ffffff')
        close_frame.pack(pady=10)
        
        close_btn = tk.Button(close_frame, 
                             text="✅ 关闭", 
                             command=progress_window.destroy,
                             font=('Microsoft YaHei UI', 10, 'bold'),
                             bg=self.colors['success'],
                             fg='white',
                             relief='flat',
                             padx=30,
                             pady=8,
                             cursor='hand2')
        close_btn.pack()
        
        return has_difference

    def validate_and_fix_scores(self):
        """验证并修复积分计算错误"""
        print("开始验证积分...")
        
        # 保存原始积分作为对比
        original_scores = {team: dict(score) for team, score in self.team_scores.items()}
        
        # 重新计算所有积分
        self.team_scores = defaultdict(lambda: {"big": 0, "small": 0})
        
        # 遍历所有历史记录重新计算
        for round_data in self.history:
            if "results" in round_data:
                for result in round_data["results"]:
                    team1 = result["team1"]
                    team2 = result["team2"]
                    
                    # 重新计算小分
                    small1 = self.card_to_score(result["result1"])
                    small2 = self.card_to_score(result["result2"])
                    
                    # 重新计算大分
                    if small1 > small2:
                        big1, big2 = 2, 0
                    elif small1 < small2:
                        big1, big2 = 0, 2
                    else:
                        big1, big2 = 1, 1
                    
                    # 累加积分
                    self.team_scores[team1]["big"] += big1
                    self.team_scores[team1]["small"] += small1
                    self.team_scores[team2]["big"] += big2
                    self.team_scores[team2]["small"] += small2
        
        # 检查是否有差异
        has_difference = False
        for team in self.teams:
            if team in original_scores:
                if (original_scores[team]["big"] != self.team_scores[team]["big"] or 
                    original_scores[team]["small"] != self.team_scores[team]["small"]):
                    print(f"队伍{team}积分差异: 原{original_scores[team]} -> 现{dict(self.team_scores[team])}")
                    has_difference = True
        
        if has_difference:
            print("发现积分差异，已修复")
            messagebox.showinfo("积分修复", "检测到积分异常并已自动修复！")
        else:
            print("积分验证通过，无异常")
        
        return has_difference

    def show_results(self):
        # 清除旧的结果显示
        for widget in self.result_content.winfo_children():
            widget.destroy()

        # 显示当前总成绩 - 使用更好的样式
        title_frame = ttk.Frame(self.result_content, style='TFrame')
        title_frame.grid(row=0, column=0, columnspan=4, pady=(0, 15), sticky="ew")
        
        ttk.Label(title_frame, 
                 text="🏆 当前总成绩", 
                 style='Title.TLabel').pack()
        
        # 表头 - 使用更好的样式
        header_frame = ttk.Frame(self.result_content, style='TFrame')
        header_frame.grid(row=1, column=0, columnspan=4, pady=(0, 10), sticky="ew")
        
        headers = [
            ("🎖️ 排名", 0),
            ("🏆 队伍", 1),
            ("📊 大分", 2),
            ("💯 小分", 3)
        ]
        
        for text, col in headers:
            ttk.Label(header_frame, 
                     text=text, 
                     style='Subtitle.TLabel').grid(row=0, column=col, padx=10, sticky=tk.W)

        # 按积分排序
        sorted_teams = sorted(self.teams, key=lambda x: (-self.team_scores[x]["big"], -self.team_scores[x]["small"]))

        # 显示每队成绩 - 使用更好的样式
        for i, team in enumerate(sorted_teams):
            row = i + 2
            score = self.team_scores[team]
            team_info = self.team_info.get(team, {})
            
            # 交替行背景色
            bg_color = '#f8f9fa' if i % 2 == 0 else '#ffffff'
            
            # 排名显示
            rank_label = ttk.Label(self.result_content, 
                                  text=f"#{i + 1}", 
                                  style='TLabel',
                                  font=('Microsoft YaHei UI', 10, 'bold'))
            rank_label.grid(row=row, column=0, padx=10, pady=3, sticky=tk.W)
            
            # 队伍信息
            team_label = ttk.Label(self.result_content, 
                                  text=f"{team}队: {team_info.get('name', '')}", 
                                  style='TLabel')
            team_label.grid(row=row, column=1, padx=10, pady=3, sticky=tk.W)
            
            # 大分显示
            big_score_label = ttk.Label(self.result_content, 
                                       text=str(score["big"]), 
                                       style='TLabel',
                                       font=('Microsoft YaHei UI', 10, 'bold'),
                                       foreground='#27ae60')
            big_score_label.grid(row=row, column=2, padx=10, pady=3, sticky=tk.W)
            
            # 小分显示
            small_score_label = ttk.Label(self.result_content, 
                                         text=str(score["small"]), 
                                         style='TLabel',
                                         foreground='#3498db')
            small_score_label.grid(row=row, column=3, padx=10, pady=3, sticky=tk.W)

    def show_ranking(self):
        if not self.team_scores:
            messagebox.showinfo("排名", "暂无比赛数据")
            return

        # 创建排名窗口
        rank_window = tk.Toplevel(self.root)
        rank_window.title("当前排名")
        rank_window.geometry("400x300")
        icon = os.path.join(os.path.dirname(__file__), 'images', 'favicon.ico')
        rank_window.iconbitmap(icon)

        # 创建主框架
        main_frame = ttk.Frame(rank_window)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 创建画布和滚动条
        canvas = tk.Canvas(main_frame)
        scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = ttk.Frame(canvas)

        # 配置画布
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(
                scrollregion=canvas.bbox("all")
            )
        )

        # 创建窗口
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        # 绑定鼠标滚轮事件
        canvas.bind("<Enter>", lambda _: canvas.bind_all("<MouseWheel>",
                                                         lambda e: canvas.yview_scroll(int(-1 * (e.delta / 120)),
                                                                                       "units")))
        canvas.bind("<Leave>", lambda _: canvas.unbind_all("<MouseWheel>"))

        # 布局
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # 按积分排序
        sorted_teams = sorted(self.teams, key=lambda x: (-self.team_scores[x]["big"], -self.team_scores[x]["small"]))

        # 显示排名标题
        title_label = ttk.Label(scrollable_frame, text="最终排名", font=('Arial', 14, 'bold'))
        title_label.pack(pady=(0, 10))

        # 创建表格框架
        table_frame = ttk.Frame(scrollable_frame)
        table_frame.pack(fill=tk.X, padx=5, pady=5)

        # 表头
        headers = ["排名", "队伍", "队员", "大分", "小分"]
        for col, header in enumerate(headers):
            ttk.Label(table_frame, text=header, font=('Arial', 10, 'bold')).grid(
                row=0, column=col, padx=5, pady=2, sticky="w")

        # 显示每队成绩
        for i, team in enumerate(sorted_teams, 1):
            score = self.team_scores[team]
            team_info = self.team_info.get(team, {})

            ttk.Label(table_frame, text=str(i)).grid(
                row=i, column=0, padx=5, pady=2, sticky="w")
            ttk.Label(table_frame, text=f"{team}队: {team_info.get('name', '')}").grid(
                row=i, column=1, padx=5, pady=2, sticky="w")
            ttk.Label(table_frame, text=", ".join(team_info.get('players', []))).grid(
                row=i, column=2, padx=5, pady=2, sticky="w")
            ttk.Label(table_frame, text=str(score["big"])).grid(
                row=i, column=3, padx=5, pady=2, sticky="w")
            ttk.Label(table_frame, text=str(score["small"])).grid(
                row=i, column=4, padx=5, pady=2, sticky="w")

        # 添加关闭按钮
        close_button = ttk.Button(scrollable_frame, text="关闭", command=rank_window.destroy)
        close_button.pack(pady=10)

    def reset_tournament(self):
        # 停止计时器
        self.timer_running = False
        self.remaining_time = 0
        self.timer_label.config(text="00:00")

        # 重置比赛数据
        self.rounds = []
        self.current_round = 0
        self.team_scores = defaultdict(lambda: {"big": 0, "small": 0})
        self.history = []
        self.start_time = None  # 重置比赛开始时间
        self.results_submitted = False  # 重置提交状态
        self.current_round_results = []  # 清空当前轮次结果
        self.edit_mode = False  # 重置编辑模式

        # 清除显示
        for widget in self.match_content.winfo_children():
            widget.destroy()
        for widget in self.result_content.winfo_children():
            widget.destroy()

        self.update_history_list()
        messagebox.showinfo("重置", "比赛已重置，可以开始新比赛！")

    def export_to_excel(self):
        if not self.team_scores:
            messagebox.showerror("错误", "没有比赛数据可导出！")
            return

        # 选择保存路径
        file_path = filedialog.asksaveasfilename(
            defaultextension=".xlsx",
            filetypes=[("Excel 文件", "*.xlsx")],
            title="保存比赛结果"
        )

        if not file_path:
            return

        try:
            wb = openpyxl.Workbook()
            ws = wb.active
            ws.title = "比赛结果"

            # 写入标题
            ws['A1'] = "掼蛋比赛结果"
            ws['A1'].font = Font(bold=True, size=14)
            ws.merge_cells('A1:E1')

            # 添加比赛时间节点信息
            if self.start_time:
                ws['A2'] = f"比赛开始时间: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}"
                ws['A2'].font = Font(italic=True)
                ws.merge_cells('A2:E2')

                ws['A3'] = f"导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
                ws['A3'].font = Font(italic=True)
                ws.merge_cells('A3:E3')

                start_row = 5  # 调整内容起始行
            else:
                start_row = 2

            # 写入队伍信息
            ws.cell(row=start_row, column=1, value="队伍信息").font = Font(bold=True)
            ws.merge_cells(f'A{start_row}:E{start_row}')
            start_row += 1

            headers = ["队伍编号", "队伍名称", "队员1", "队员2"]
            for col, header in enumerate(headers, 1):
                ws.cell(row=start_row, column=col, value=header).font = Font(bold=True)

            for row, team in enumerate(self.teams, start_row + 1):
                team_info = self.team_info.get(team, {})
                ws.cell(row=row, column=1, value=team)
                ws.cell(row=row, column=2, value=team_info.get("name", ""))
                players = team_info.get("players", ["", ""])

                ws.cell(row=row, column=3, value=players[0])
                ws.cell(row=row, column=4, value=players[1])

            # 写入比赛结果
            row_start = len(self.teams) + start_row + 2
            for i, round_data in enumerate(self.history, 1):
                ws.cell(row=row_start, column=1, value=f"第 {i} 轮比赛").font = Font(bold=True)
                ws.merge_cells(f'A{row_start}:E{row_start}')
                row_start += 1

                headers = ["队伍1", "结果1", "队伍2", "结果2", "大分1", "小分1", "大分2", "小分2"]
                for col, header in enumerate(headers, 1):
                    ws.cell(row=row_start, column=col, value=header).font = Font(bold=True)
                row_start += 1

                for match in round_data.get("results", []):
                    team1_info = self.team_info.get(match["team1"], {})
                    team2_info = self.team_info.get(match["team2"], {})

                    ws.cell(row=row_start, column=1, value=f"{match['team1']}队: {team1_info.get('name', '')}")
                    ws.cell(row=row_start, column=2, value=match["result1"])
                    ws.cell(row=row_start, column=3, value=f"{match['team2']}队: {team2_info.get('name', '')}")
                    ws.cell(row=row_start, column=4, value=match["result2"])
                    ws.cell(row=row_start, column=5, value=match["big1"])
                    ws.cell(row=row_start, column=6, value=match["small1"])
                    ws.cell(row=row_start, column=7, value=match["big2"])
                    ws.cell(row=row_start, column=8, value=match["small2"])
                    row_start += 1
                row_start += 1

            # 写入最终排名
            row_start += 1
            ws.cell(row=row_start, column=1, value="最终排名").font = Font(bold=True, size=12)
            ws.merge_cells(f'A{row_start}:E{row_start}')
            row_start += 1

            headers = ["排名", "队伍", "队员", "大分", "小分"]
            for col, header in enumerate(headers, 1):
                ws.cell(row=row_start, column=col, value=header).font = Font(bold=True)
            row_start += 1

            sorted_teams = sorted(self.teams,
                                  key=lambda x: (-self.team_scores[x]["big"], -self.team_scores[x]["small"]))
            for i, team in enumerate(sorted_teams, 1):
                team_info = self.team_info.get(team, {})
                ws.cell(row=row_start, column=1, value=i)
                ws.cell(row=row_start, column=2, value=f"{team}队: {team_info.get('name', '')}")
                ws.cell(row=row_start, column=3, value=", ".join(team_info.get("players", [])))
                ws.cell(row=row_start, column=4, value=self.team_scores[team]["big"])
                ws.cell(row=row_start, column=5, value=self.team_scores[team]["small"])
                row_start += 1

            # 保存文件
            wb.save(file_path)
            messagebox.showinfo("成功", f"比赛结果已成功导出到:\n{file_path}")

        except Exception as e:
            messagebox.showerror("错误", f"导出失败: {str(e)}")

    def save_tournament(self):
        if not self.team_scores:
            messagebox.showerror("错误", "没有比赛数据可保存！")
            return

        # 准备保存数据
        save_data = {
            "teams": self.teams,
            "rounds": self.rounds,
            "current_round": self.current_round,
            "max_rounds": self.max_rounds.get(),
            "team_scores": dict(self.team_scores),
            "team_info": self.team_info,
            "history": self.history,
            "start_time": self.start_time.strftime("%Y-%m-%d %H:%M:%S") if self.start_time else None,
            # 新增：保存关键状态变量以防止积分计算错误
            "results_submitted": self.results_submitted,
            "current_round_results": self.current_round_results,
            "edit_mode": self.edit_mode
        }

        # 选择保存路径
        file_path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON 文件", "*.json")],
            title="保存比赛进度"
        )

        if not file_path:
            return

        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(save_data, f, ensure_ascii=False, indent=2)
            messagebox.showinfo("成功", f"比赛进度已保存到:\n{file_path}")
        except Exception as e:
            messagebox.showerror("错误", f"保存失败: {str(e)}")

    def load_tournament(self):
        # 选择加载文件
        file_path = filedialog.askopenfilename(
            filetypes=[("JSON 文件", "*.json")],
            title="加载比赛进度"
        )

        if not file_path:
            return

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                save_data = json.load(f)

            # 恢复数据
            self.teams = save_data["teams"]
            self.rounds = save_data["rounds"]
            self.current_round = save_data["current_round"]
            self.max_rounds.set(save_data.get("max_rounds", 3))  # 加载轮次设置
            self.team_scores = defaultdict(lambda: {"big": 0, "small": 0}, save_data["team_scores"])
            self.team_info = save_data["team_info"]
            self.history = save_data["history"]

            # 恢复比赛开始时间
            if save_data.get("start_time"):
                self.start_time = datetime.strptime(save_data["start_time"], "%Y-%m-%d %H:%M:%S")
            else:
                self.start_time = None

            # 恢复关键状态变量 - 修复积分计算问题
            self.results_submitted = save_data.get("results_submitted", False)
            self.current_round_results = save_data.get("current_round_results", [])
            self.edit_mode = save_data.get("edit_mode", False)

            # 清除旧的显示内容
            for widget in self.match_content.winfo_children():
                widget.destroy()
            for widget in self.result_content.winfo_children():
                widget.destroy()

            # 更新UI
            self.update_history_list()
            self.show_results()
            
            # 验证加载的积分数据
            self.validate_and_fix_scores()

            # 重新生成队伍数量选择
            self.team_count.set(len(self.teams))
            self.rounds_entry.delete(0, tk.END)
            self.rounds_entry.insert(0, str(self.max_rounds.get()))

            messagebox.showinfo("成功", f"比赛进度已从以下文件加载:\n{file_path}")
        except Exception as e:
            messagebox.showerror("错误", f"加载失败: {str(e)}")

    def update_history_list(self):
        self.history_listbox.delete(0, tk.END)
        for record in self.history:
            self.history_listbox.insert(tk.END, f"第{record['round']}轮 - {record['timestamp']}")

if __name__ == "__main__":
    root = tk.Tk()
    app = GuanDanTournament(root)
    root.mainloop()